<template>
    <div class="order-form-container">

        <!-- 表单区域 -->
        <div class="form-content">

            <div class="form-item">
                <div class="item-label">游戏类型<span class="required-star">*</span></div>
                <van-field readonly clickable :value="gameTypeText" placeholder="请选择游戏类型" @click="showGameTypePicker = true"
                    class="form-input" is-link />
                <van-popup v-model="showGameTypePicker" position="bottom">
                    <van-picker show-toolbar :columns="gameTypeOptions" @confirm="onGameTypeConfirm"
                        @cancel="showGameTypePicker = false" />
                </van-popup>
            </div>

            <div class="form-item">
                <div class="item-label">游戏名称<span class="required-star">*</span></div>
                <van-field readonly clickable :value="gameText" placeholder="请选择游戏名称" @click="showGamePicker = true"
                    class="form-input" is-link />
                <van-popup v-model="showGamePicker" position="bottom">
                    <van-picker show-toolbar :columns="filterGameList" @confirm="onGameConfirm"
                        @cancel="showGamePicker = false" />
                </van-popup>
            </div>

            <div class="form-item">
                <div class="item-label">商品名称<span class="required-star">*</span></div>
                <van-field readonly clickable :value="idleText" placeholder="请选择商品名称" @click="showIdlePicker = true"
                    class="form-input" is-link />
                <van-popup v-model="showIdlePicker" position="bottom">
                    <van-picker show-toolbar :columns="filterIdleList" @confirm="onIdleConfirm"
                        @cancel="showIdlePicker = false" />
                </van-popup>
            </div>

            <div class="form-item">
                <div class="item-label">排位类型<span class="required-star">*</span></div>
                <van-field readonly clickable :value="gameNumText" placeholder="请选择排位类型" @click="showGameNumPicker = true"
                    class="form-input" is-link />
                <van-popup v-model="showGameNumPicker" position="bottom">
                    <van-picker show-toolbar :columns="gameNumOptions" @confirm="onPlayerNumConfirm"
                        @cancel="showGameNumPicker = false" />
                </van-popup>
            </div>

            <!-- 订单金额 -->
            <div class="form-item">
                <div class="item-label">订单金额<span class="required-star">*</span></div>
                <van-field v-model="form.price" readonly placeholder="￥0.00" type="number" class="form-input" />
            </div>

            <!-- 支付方式
            <div class="form-item">
                <div class="item-label">支付方式<span class="required-star">*</span></div>
                <van-field readonly clickable :value="form.payment" placeholder="请选择支付方式" @click="showPaymentPicker = true"
                    class="form-input" is-link />
                <van-popup v-model="showPaymentPicker" position="bottom">
                    <van-picker show-toolbar :columns="paymentOptions" @confirm="onPaymentConfirm"
                        @cancel="showPaymentPicker = false" />
                </van-popup>
            </div> -->

            <!-- 客户游戏ID -->
            <div class="form-item">
                <div class="item-label">游戏ID<span class="required-star">*</span></div>
                <van-field v-model="form.laobanyouxiid" placeholder="请输入游戏ID" class="form-input" />
            </div>

            <!-- 语音类型 -->
            <div class="form-item">
                <div class="item-label">语音类型<span class="required-star">*</span></div>
                <van-field readonly clickable :value="form.channel" placeholder="请选择语音类型"
                    @click="showVoiceTypePicker = true" class="form-input" is-link />
                <van-popup v-model="showVoiceTypePicker" position="bottom">
                    <van-picker show-toolbar :columns="voiceTypeOptions" @confirm="onVoiceTypeConfirm"
                        @cancel="showVoiceTypePicker = false" />
                </van-popup>
            </div>

            <!-- 语音类型 -->
            <div class="form-item">
                <div class="item-label">指定打手</div>
                <van-field readonly clickable :value="playerText" placeholder="请选择指定打手"
                    @click="showZhidingdashouPicker = true" class="form-input" is-link />
                <!-- <van-popup v-model="showZhidingdashouPicker" position="bottom">
                    <van-picker show-toolbar :columns="playerOptions" @confirm="onPlayerConfirm"
                        @cancel="showZhidingdashouPicker = false" />
                </van-popup> -->

                <van-popup v-model:show="showZhidingdashouPicker" position="bottom">
                    <div style="
                display: flex;
                justify-content: space-between;
                height: 44px;
                line-height: 44px;
              ">
                        <van-button style="border: none; color: #969799" @click="showPicker = false"
                            size="normal">取消</van-button>
                        <!-- <div style="border: none; color: #000" size="normal">确认</div> -->
                        <van-button style="border: none; color: #6398fb" @click="checkedChange"
                            size="normal">确认</van-button>
                    </div>
                    <van-checkbox-group v-model="selectPlayer">
                        <van-cell v-for="(item, index) in playerOptions" :key="index" :title="`${item.nickName}`">
                            <template #right-icon>
                                <van-checkbox :name="item.id" />
                            </template>
                        </van-cell>
                    </van-checkbox-group>
                </van-popup>
            </div>

            <!-- 备注信息 -->
            <div class="form-item">
                <div class="item-label">备注信息</div>
                <van-field v-model="form.createRemark" type="textarea" placeholder="请输入补充说明（选填）" rows="2" autosize
                    class="form-input remark-input" />
            </div>

            <!-- 提交按钮 -->
            <div class="form-submit">
                <van-button block type="primary" class="submit-btn" @click="handleSubmit">
                    确认发布
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { Toast } from 'vant';
import userApi from '@/plugins/api/user'
import orderApi from '@/plugins/api/order' // 添加缺失的导入
import dealApi from '@/plugins/api/deal'
import idleApi from '@/plugins/api/idle'
import gameApi from '@/plugins/api/game'
import { orderCaozuo, updateSelf } from '@/plugins/utils/caozuojilu'
import configApi from '@/plugins/api/config'

export default {
    data() {
        return {
            form: {
                gameType: null,       // 游戏类型（选择值）
                gameId: null,         // 游戏ID（选择值）
                idleId: null,
                gameAccount: '',      // 游戏账号（输入值）
                laobanyouxiid: '',    // 游戏Id（输入值）
                price: '',             // 订单金额（数字，禁用）
                dashouyongjin: '',     // 打手佣金（数字，禁用）
                playerNum: null,      // 单排/双排（选择值）
                channel: '',        // 语音频道（选择值）
                payment: '余额支付',        // 支付方式（选择值）
                playerId: '',       // 指定打单人
                userId: null,    // 发单人ID（选择值）
                createRemark: ''      // 订单备注（输入值）
            },
            allUser: [],
            showPaymentPicker: false,
            showVoiceTypePicker: false,
            showGamePicker: false,
            showGameTypePicker: false,
            showZhidingdashouPicker: false,
            paymentOptions: [
                { text: '闲鱼下单', value: '闲鱼下单' },
                { text: '闲鱼转账', value: '闲鱼转账' },
                { text: '支付宝转账', value: '支付宝转账' },
                { text: '微信转账', value: '微信转账' },
            ],
            selectPlayer: [],
            voiceTypeOptions: [
                { text: 'kook', value: 'kook' },
                { text: 'yy', value: 'yy' },
                { text: '游戏麦', value: '游戏麦' }
            ],
            gameNumOptions: [
                { text: '单排', value: 1 },
                { text: '双排', value: 2 },
            ],
            gameTypeOptions: [
                { text: '端游', value: 1 },
                { text: '手游', value: 2 },
            ],
            gameOptions: [],
            self: this.$global.self,
            showGameNumPicker: false,
            idles: [],
            showIdlePicker: false,
            adding: false
        }
    },
    computed: {
        // paymentText() {
        //     const option = this.paymentOptions.find(item => item.value === this.form.payment);
        //     return option ? option.text : '';
        // },
        // voiceTypeText() {
        //     const option = this.voiceTypeOptions.find(item => item.value === this.form.channel);
        //     return option ? option.text : '';
        // },
        gameTypeText() {
            const option = this.gameTypeOptions.find(item => item.value === this.form.gameType)
            return option ? option.text : ''
        },
        gameNumText() {
            const option = this.gameNumOptions.find(item => item.value === this.form.playerNum)
            return option ? option.text : ''
        },
        gameText() {
            const option = this.gameOptions.find(item => item.value === this.form.gameId);
            return option ? option.gameName : '';
        },
        idleText() {
            const option = this.idles.find(item => item.value === this.form.idleId);
            return option ? option.idleName : '';
        },
        filterGameList() {
            return this.gameOptions.filter(item => item.type === this.form.gameType)
        },
        filterIdleList() {
            return this.idles.filter(item => item.gameId === this.form.gameId)
        },
        playerOptions() {
            return this.allUser.filter(item => item.role === 2 && item.stop == true)
        },
        playerText() {
            let str = ''
            if (this.selectPlayer.length > 0) {
                for (let i = 0; i < this.selectPlayer.length; i++) {
                    const obj = this.allUser.find(item => item.id === this.selectPlayer[i])
                    if (obj) {
                        str += !str ? obj.nickName : ',' + obj.nickName
                    }
                }
            }
            return str
        }
    },
    async mounted() {
        await this.getIdleList()
        await this.getGameList()
        await this.getAllUser()
        this.form.userId = this.self.id
        await this.getConfig()
    },
    methods: {
        async getConfig() {
            const res = await configApi.list()
            if (res.code === 200) {
                this.config = res.data
            } else {
                this.$toast.fail('获取系统配置出错')
            }
        },
        async getIdleList() {
            const res = await idleApi.list()
            console.log('res -> ', res);
            if (res.code === 200) {
                for (let index = 0; index < res.data.length; index++) {
                    res.data[index].text = res.data[index].idleName
                    res.data[index].value = res.data[index].id
                }
                this.idles = res.data.filter(item => item.status)
                console.log(this.idles);

            } else {
                this.$toast.fail('获取商品列表出错')
            }
        },

        checkedChange() {
            console.log(this.selectPlayer);
            this.form.playerId = this.selectPlayer.length > 0 ? this.selectPlayer.join(',') : ''
            this.showZhidingdashouPicker = false
        },
        getYajinConfig() {
            const fadan = this.config.find(item => item.name === 'fadan')
            console.log(Number(fadan.value) / 100);
            return Number(fadan.value) / 100
        },

        getGongsiConfig() {
            const gongsi = this.config.find(item => item.name === 'gongsi')
            console.log(Number(gongsi.value) / 100);

            return Number(gongsi.value) / 100
        },

        async getGameList() {
            const res = await gameApi.list()
            if (res.code === 200) {
                for (let index = 0; index < res.data.length; index++) {
                    res.data[index].text = res.data[index].gameName
                    res.data[index].value = res.data[index].id
                }
                this.gameOptions = res.data
            } else {
                this.$toast.fail('获取游戏列表出错')
            }
        },

        async getAllUser() {
            const res = await userApi.all()
            console.log('getAllUser -> ', res);
            if (res.code === 200) {
                for (let index = 0; index < res.data.length; index++) {
                    res.data[index].name = res.data[index].nickName
                    res.data[index].value = res.data[index].id
                }
                this.allUser = res.data
            } else {
                this.$toast.fail('获取用户列表出错')
            }
        },
        onPaymentConfirm(value) {
            this.form.payment = value.value;
            this.showPaymentPicker = false;
        },
        onGameTypeConfirm(value) {
            this.form.gameType = value.value;
            this.showGameTypePicker = false;
        },
        onPlayerNumConfirm(value) {
            this.form.playerNum = value.value;
            this.showGameNumPicker = false;
        },
        onGameConfirm(value) {
            // const game = this.gameOptions.find(item => item.id === value.value)
            this.form.gameId = value.value;
            // this.form.price = game.price
            // this.form.dashouyongjin = (Number(game.price) * (1 - this.getYajinConfig())).toFixed(2)
            this.showGamePicker = false;
        },
        onIdleConfirm(value) {
            const game = this.idles.find(item => item.id === value.value)
            this.form.idleId = value.value;
            this.form.price = game.price
            this.form.dashouyongjin = (Number(game.price) * (1 - this.getYajinConfig() - this.getGongsiConfig())).toFixed(2)
            this.showIdlePicker = false;
        },
        onVoiceTypeConfirm(value) {
            this.form.channel = value.value;
            this.showVoiceTypePicker = false;
        },
        onPlayerConfirm(value) {
            this.form.playerId = value.value;
            this.showZhidingdashouPicker = false;
        },
        async handleSubmit() {
            if (!this.adding) {
                this.adding = true
                setTimeout(async () => {
                    const that = this
                    if (!that.validateForm()) return;
                    that.form.orderStatus = 1
                    that.form.orderNo = new Date().getTime()
                    console.log('订单数据:', that.form);
                    if (that.self.balance >= that.form.price) {
                        that.self.balance = Number(that.self.balance) - Number(that.form.price)
                        const dealObj = {
                            userId: that.self.id,
                            value: `-${Number(that.form.price)}`,
                            type: 1,
                            createTime: new Date().getTime()
                        }
                        const dealRes = await dealApi.modify(dealObj)
                        if (dealRes.code === 200) {
                            if (that.form.playerNum === that.selectPlayer.length) {
                                that.form.orderStatus = 2
                            } else {
                                that.form.orderStatus = 1
                            }
                            const res = await orderApi.modify(that.form)
                            if (res.code === 200) {
                                await orderCaozuo.add(that.form)
                                const userRes = await userApi.update(that.self)
                                if (userRes.code === 200) {
                                    await updateSelf(userRes.data)
                                    that.$toast.success('创建成功')
                                    that.$router.back()
                                }
                            } else {
                                that.$toast.fail(res.msg)
                            }
                        } else {
                            that.$toast.fail(dealRes.msg)
                        }

                    } else {
                        that.$toast.fail('您的积分不够')
                    }
                }, 500);
            }
        },
        validateForm() {
            if (!this.form.userId) {
                Toast.fail('请输入客户姓名');
                return false;
            }
            if (!this.form.payment) {
                Toast.fail('请选择支付方式');
                return false;
            }
            if (!this.form.gameId) {
                Toast.fail('请选择游戏');
                return false;
            }
            if (!this.form.idleId) {
                Toast.fail('请选择商品');
                return false;
            }
            if (!this.form.channel) {
                Toast.fail('请选择语音类型');
                return false;
            }
            if (!this.form.gameType) {
                Toast.fail('请选择游戏类型');
                return false;
            }
            if (!this.form.laobanyouxiid) {
                Toast.fail('请选择游戏ID');
                return false;
            }
            if (!this.form.playerNum) {
                Toast.fail('请选择排位类型');
                return false;
            }

            if (this.selectPlayer.length > this.form.playerNum) {
                Toast.fail('指定打手错误');
                return false;
            }

            return true;
        }
    }
}
</script>

<style lang="scss" scoped>
.order-form-container {
    padding: 16px;
    background: #fff;
    min-height: 100vh;
}

.form-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 24px;
    color: #333;
}

.form-content {
    background: #fff;
}

.form-item {
    margin-bottom: 20px;
}

.item-label {
    font-size: 14px;
    color: #333;
    margin-bottom: 8px;

    .required-star {
        color: #f44;
        margin-left: 4px;
    }
}

.form-input {
    background: #f7f8fa;
    border-radius: 4px;
    padding: 12px 16px;

    &::placeholder {
        color: #969799;
    }
}

.amount-input {
    ::v-deep .van-field__control {
        color: #f44;
    }
}

.remark-input {
    ::v-deep .van-field__control {
        min-height: 60px;
    }
}

.form-submit {
    margin-top: 32px;
}

.submit-btn {
    background: #1989fa;
    border: none;
    border-radius: 4px;
    height: 44px;
    font-size: 16px;
}
</style>
